package com.es.util.format;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;

public class Format implements java.io.Serializable {
    public Format() {}

    /**
     * @param source
     *            需要处理的字符串
     * @param oldString
     *            需要被替换的字符
     * @param newString
     *            替换后的字符
     * @return 比如 需要替换字符串中的? String str = "Who am I ?"; replace(str,"?","%3F");
     */
    public static String replace(
            String source, String oldString, String newString) {
        StringBuffer output = new StringBuffer();
        int lengthOfSource = source.length();
        int lengthOfOld = oldString.length();
        int posStart = 0;
        int pos; //
        while ((pos = source.indexOf(oldString, posStart)) >= 0)
        {
            output.append(source.substring(posStart, pos));
            output.append(newString);
            posStart = pos + lengthOfOld;
        }
        if (posStart < lengthOfSource)
        {
            output.append(source.substring(posStart));
        }
        return output.toString();
    }

    public static String toScript(String str) {
        if (str == null)
            return null;
        String html = new String(str);
        html = replace(html, "\r\n", "\\r\\n");
        html = replace(html, "\n", "\\n");
        html = replace(html, "\t", "\\t");
        return html;
    }

    public static String toScriptVB(String str) {
        if (str == null)
            return null;
        String html = new String(str);
        html = replace(html, "\r\n", "\"&chr(10)&chr(13)&\"");

        html = replace(html, "\n", "\\n");
        html = replace(html, "\t", "\\t");
        return html;
    }

    /**
     * 在JSP页面中在text中显示的数据转换
     * 
     * @param str
     * @return
     */
    public static String toHtmlInput(String str) {
        if (str == null)
            return null;
        String html = new String(str);

        // html = replace(html, "&", "&amp;");
        html = replace(html, "<", "&lt;");
        html = replace(html, ">", "&gt;");
        html = replace(html, "\"", "&quot;");

        return html;
    }

    public static String toHtmlInputField(String str) {
        if (str == null)
            return null;
        String html = new String(str);
        html = toHtml(html);
        html = replace(html, "\"", "\\\"");
        html = replace(html, "\'", "\\\'");

        return html;
    }

    public static String toXml(String str) {
        if (str == null)
            return null;
        String html = new String(str);
        html = replace(html, "&", "&amp;");
        html = replace(html, "<", "&lt;");
        html = replace(html, ">", "&gt;");

        return html;
    }

    /**
     * 在JSP页面中在textarea中显示的数据转换
     * 
     * @param str
     * @return
     */
    public static String toHtml(String str) {
        if (str == null)
            return "";
        String html = new String(str);
        html = toHtmlInput(html);
        html = html.replaceAll(" ", "&nbsp;");
        html = html.replaceAll("\r\n", "<br>");
        html = html.replaceAll("\n", "<br>");
        // html = html.replaceAll("\r\n","<br>");
        return html;
    }

    /**
     * 将str分段，在html页面进行换行显示
     * 
     * @param str
     *            需要截取的字符串
     * @param width
     *            需要的宽度
     * @return
     */
    public static String sub2html(String str, int width) {
        if (str == null)
            return "";
        String html = toHtml(str);
        return null;
    }

    public static String toSql(String str) {
        if (str == null)
            return null;
        str = str.replaceAll("%", "[%]");
        str = str.replaceAll("_", "[_]");
        str = str.replaceAll("'", "''");
        return str;
    }

    public static String toSql(String str, String str1) {
        if (str == null)
            return null;
        return replace(str, "%", "[%]");
    }

    public static String iso2gb(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes("ISO8859_1"), "GBK");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String iso2utf(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes("ISO8859_1"), "utf-8");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String GBK2utf(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes("GBK"), "UTF-8");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String utf2iso(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes("utf-8"), "ISO8859_1");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String toGb(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes(), "GBK");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String gb2iso(String value) {
        if (value == null)
            return "";
        try
        {
            value = new String(value.getBytes("GBK"), "ISO8859_1");
        } catch (Exception e)
        {
            e.printStackTrace(System.err);
            return "";
        }
        return value;
    }

    public static String getFileExp(String filename) {
        StringTokenizer token = new StringTokenizer(filename, ".");
        String exp = null;
        while (token.hasMoreTokens())
        {
            exp = token.nextToken();
        }
        return exp;
    }

    public static String getDateTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date Now = new java.util.Date();
        String NDate = formatter.format(Now);
        return NDate;
    }

    public static String getDateTime(int type) {
        DateFormat formatter = DateFormat.getDateInstance(type);
        java.util.Date Now = new java.util.Date();
        String NDate = formatter.format(Now);
        return NDate;
    }

    public static String getDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date Now = new java.util.Date();
        String NDate = formatter.format(Now);
        return NDate;
    }

    public static String getDate(String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        java.util.Date Now = new java.util.Date();
        String NDate = formatter.format(Now);
        return NDate;
    }

    public static String getNextDate(String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(cal.MONTH, 1);
        java.util.Date Now = cal.getTime();

        String NDate = formatter.format(Now);
        return NDate;
    }


    public static String conNull(String str) {
        if (str == null)
        {
            return "";
        } else
        {
            return str;
        }
    }

    public static String getAttr(HttpSession session, String attr) {
        return conNull(session.getAttribute(attr));
    }

    public static String conNull(Object str) {
        if (str == null)
        {
            return "";
        } else
        {
            return (String) str;
        }
    }

    public static String replaceSecurityStr(String myParameter) {
        if (myParameter == null)
        {
            return "";
        } else
        {
            myParameter = myParameter.trim();
            myParameter = myParameter.replace('<', '_');
            myParameter = myParameter.replace('>', '_');
            myParameter = myParameter.replace('"', '_');
            myParameter = myParameter.replace('\'', '_');
            myParameter = myParameter.replace('%', '_');
            myParameter = myParameter.replace(';', '_');
            myParameter = myParameter.replace('(', '_');
            myParameter = myParameter.replace(')', '_');
            myParameter = myParameter.replace('&', '_');
            myParameter = myParameter.replace('+', '_');
            return myParameter;
        }
    }

    private static NumberFormat nf = NumberFormat.getPercentInstance();
    static
    {
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
    }

    public static String formatFloat(float value) {
        String per = nf.format(value);
        if (per.equals("?"))
            return "0";
        return per;
    }

    public static String[] split(String source, String div) {
        int arynum = 0, intIdx = 0, intIdex = 0, div_length = div.length();
        if (source.compareTo("") != 0)
        {
            if (source.indexOf(div) != -1)
            {
                intIdx = source.indexOf(div);
                for (int intCount = 1;; intCount++)
                {
                    if (source.indexOf(div, intIdx + div_length) != -1)
                    {
                        intIdx = source.indexOf(div, intIdx + div_length);
                        arynum = intCount;
                    } else
                    {
                        arynum += 2;
                        break;
                    }
                }
            } else
            {
                arynum = 1;
            }
        } else
        {
            arynum = 0;
        }
        intIdx = 0;
        intIdex = 0;
        String[] returnStr = new String[arynum];

        if (source.compareTo("") != 0)
        {
            if (source.indexOf(div) != -1)
            {
                intIdx = (int) source.indexOf(div);
                returnStr[0] = (String) source.substring(0, intIdx);
                for (int intCount = 1;; intCount++)
                {
                    if (source.indexOf(div, intIdx + div_length) != -1)
                    {
                        intIdex = (int) source.indexOf(div, intIdx + div_length);
                        returnStr[intCount] = (String) source.substring(intIdx + div_length, intIdex);
                        intIdx = (int) source.indexOf(div, intIdx + div_length);
                    } else
                    {
                        returnStr[intCount] = (String) source.substring(intIdx + div_length, source.length());
                        break;
                    }
                }
            } else
            {
                returnStr[0] = (String) source.substring(0, source.length());
                return returnStr;
            }
        } else
        {
            return returnStr;
        }
        return returnStr;
    }

    /**
     * 替换URL中的特殊字符
     * 
     * @param str
     * @return
     */
    public static String toUrl(String str) {
        // .replaceAll("+","%2B").replaceAll("?","%3F")
        if (str == null)
            return "";
        str = str.replaceAll("%", "%25").replaceAll(" ", "%20").replaceAll("/", "%2F").replaceAll("#", "%23").replaceAll("&", "%26").replaceAll("=", "%3D");
        str = replace(str, "+", "%2B");
        str = replace(str, "?", "%3F");
        return str;
    }

    public static void main(String[] args) {
        // public static String getDate(String pattern) {
        // SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        // java.util.Date Now = new java.util.Date();
        // String NDate = formatter.format(Now);
       // System.out.println(getNextDate("yyyy-MM"));
        String str="<font style='color:red'> 内容</font>";
        System.out.println(replaceSecurityStr(str));

    }

    public static String createResponseMessageAsXML(
    		HashMap<String,List<String>>message) {
        StringBuffer resXml = new StringBuffer();
        resXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        resXml.append("<response>");
        for(String str : message.keySet())
        	for(String value : message.get(str))
        		resXml.append("<"+str+">" + value + "</"+str+">");
        resXml.append("</response>");
        System.out.println(resXml.toString());
        return resXml.toString();
    }
}
